package finance

import org.apache.commons.math.stat.correlation.SpearmansCorrelation

class ShuffleService {
    
    static transactional = true
    def ITERATIONS = 4
    
    def periods(close) {
        def totals = [:]
        def rand = new Random(System.currentTimeMillis())
        def corr = new SpearmansCorrelation()
        
        for(j in 0..ITERATIONS) {
            shuffle(close, totals, corr, rand)
        }
        
        def sortedMap = totals.sort { a, b -> b.value <=> a.value }
        def normalized = [:]
        
        sortedMap.each { key, value ->
            normalized[key] = value/ITERATIONS
        }
        
        def top6 = normalized.keySet() as List
        return top6[0..5]
    }
    
    def hack(close, n)   {
        def listOfLists = []
        
        for(i in (0 ..<close.size()).step(n)) {
            def end = i + n
            if(end > close.size()) end = close.size()
            
            listOfLists << close[i..<end]
        }
        
        return listOfLists
    } 
    
    def shuffle(close, totals, corr, rand) { 
        for(n in 5..close.size()) {
            def listOfLists = hack(close, n) 
            
            Collections.shuffle(listOfLists, rand)
            
            listOfLists = listOfLists.flatten()
            
            if(!totals[n]) {
                totals[n] = 0
            }
            
            def correctionFactor = close.size()/n
            def val = corr.correlation(close as double[], listOfLists as double []) * correctionFactor
            totals[n] += val
        }
    }
}
